<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/10
 * Time: 13:41
 */

namespace common\business\mdm;


use common\business\CommonHelper;
use common\business\ifs\CrudInterface;
use common\consts\CommonResources;
use common\models\Log;
use common\result\ActionResult;
use yii\db\ActiveRecord;
use Yii;

class MdmHandler
{
    /**
     * @var MdmCrud
     */
    protected $_crud;

    /**
     * @param $crud MdmCrud
     */
    public function setCrud($crud){
        $this->_crud = $crud;
    }

    /**
     * @param $obj ActiveRecord
     * @return ActionResult
     */
    public function create($obj){
        return $this->_crud->create($obj);
    }

    /**
     * @param $oldObj ActiveRecord
     * @param $newObj ActiveRecord
     * @param $compareArr array
     * @param $updateLog Log
     * @return ActionResult
     */
    public function update($newObj, $oldObj, $compareArr, $updateLog = null){
        $action = Yii::t('app', 'Update');
        $modelClass = Yii::t('app', get_class($newObj));

//检查对象属性是否变化
        $compareResult = CommonHelper::compareObjectAttributes($oldObj, $newObj, $compareArr);
        if (!$compareResult->isChanged){
            return new ActionResult(true, CommonResources::OBJECT_NOT_CHANGED($modelClass), true);
        }

        //记住id不能变
//        $dbId = $oldObj->employee_id;
//        $oldObj->setAttributes($newObj->getAttributes());
        foreach ($compareArr as $attr){
            $oldObj->setAttribute($attr, $newObj->getAttribute($attr));
        }
//        $oldObj->employee_id = $dbId;
        if (!$updateLog){
            $updateLog = new Log([
                'action' => CommonResources::ACTION_NAME_MSG($action, $modelClass, CommonHelper::getPrintName($oldObj)),
                'old_content' => $compareResult->old_content,
                'new_content' => $compareResult->new_content,
                'memo' => $compareResult->message,
            ]);
        }
        $result = $this->_crud->updateWithLog($oldObj, $updateLog);
        return $result;
    }
}